package cn.workreport.modules.upload.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.workreport.modules.common.annotations.UserLoginToken;
import cn.workreport.modules.common.controller.BaseController;
import cn.workreport.modules.common.po.IdsPO;
import cn.workreport.modules.common.po.PagePO;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.upload.entity.Upload;
import cn.workreport.modules.upload.enums.BusinessKeyEnum;
import cn.workreport.modules.upload.service.IUploadService;
import cn.workreport.util.JsonResult;
import cn.workreport.util.PageQueryUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 文件上传 前端控制器
 * </p>
 *
 * @author yyf
 * @since 2022-01-19
 */
@Slf4j
@RestController
@UserLoginToken
@Api(tags = "文件上传模块")
public class UploadController extends BaseController {

    @Autowired
    private IUploadService uploadService;

    /**
     * 上传单张图片
     *
     * @param file
     * @return
     */
    @ApiOperation("上传单张图片")
    @PostMapping("/upload/image")
    public JsonResult<?> uploadImage(MultipartFile file, BusinessKeyEnum businessKey, String type) {
        Upload uploadEntity = uploadService.uploadImage(file, businessKey, type);
        if (ObjectUtil.isEmpty(uploadEntity)) {
            return JsonResult.fail("文件上传失败");
        }
        return JsonResult.ok(uploadEntity);
    }

//    public JsonResult<?> uploadImage(
//             MultipartFile file, HttpSession session
//    ) {
//        // 判断是否为空
//        if (file.isEmpty()) {
//            return JsonResult.fail("文件不能为空");
//        }
//        // 获取原始文件名
//        String fileOriginName = file.getOriginalFilename();
//        // 获取文件名后缀
//        String suffix = "";
//        int suffixIndex = fileOriginName.lastIndexOf(".");
//        if (suffixIndex > 0) {
//            suffix = fileOriginName.substring(suffixIndex);
//        }
//        log.info("suffix ===>" + suffix);
//        // 得到新文件名
//        String fileName = UUID.randomUUID().toString() + suffix;
//        String realPath = session.getServletContext().getRealPath("upload/images");
//        log.info("realPath ===>" + realPath);
//        File realPathDir = new File(realPath);
//        if (!realPathDir.exists()) {
//            realPathDir.mkdirs();
//        }
//        // 保存文件到服务器
//        File dest = new File(realPathDir, fileName);
//        try {
//            file.transferTo(dest);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("保存文件到服务器失败！");
//        }
//
//        String filePath = "upload/images" + fileName;
//        return JsonResult.ok(filePath);
//    }

    /**
     * 保存或修改文件上传
     *
     * @param entity 实体信息
     * @return 成功与否，成功返回实体信息，失败返回错误信息
     */
    @ApiOperation("修改或保存文件上传")
    @PostMapping("/upload/saveOrUpdate")
    public JsonResult<?> saveOrUpdate(Upload entity) {
        log.info("===> 进入 /upload/saveOrUpdate ===> params = " + entity);
        return uploadService.saveOrUpdateEntity(entity);
    }

    /**
     * 分页查询文件上传
     *
     * @param pagePO
     * @return 查询结果
     */
    @ApiOperation("分页查询文件上传")
    @PostMapping("/upload/listPage")
    public JsonResult<?> listPage(PagePO<Upload> pagePO) {
        log.info("===> 进入 /upload/listPage ===> params = " + pagePO);
        IPage<Upload> page = new PageQueryUtil<Upload>().getPage(pagePO);
        LambdaQueryWrapper<Upload> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Upload::getCreatedTime);
        PageVO<Upload> result = uploadService.pageEntity(page, wrapper);
        return JsonResult.ok(result);
    }

    /**
     * 根据ID查询文件上传
     * 如果查询不到，new 一个返回，可以作为新建请求
     *
     * @param id ID
     * @return 查询结果
     */
    @ApiOperation("根据ID查询文件上传")
    @GetMapping("/upload/getById")
    public JsonResult<?> getById(Integer id) {
        log.info("===> 进入 /upload/getById ===> params = " + id);
        // 暂时未用到
        return JsonResult.ok();
    }

    /**
     * 批量或单体删除文件上传
     *
     * @param idsPO ID集合
     * @return 成功与否
     */
    @ApiOperation("批量删除文件上传")
    @PostMapping("/upload/removeByIds")
    public JsonResult<?> removeByIds(IdsPO idsPO) {
        log.info("===> 进入 /upload/removeByIds ===> params = " + idsPO);
        if (ObjectUtils.isEmpty(idsPO)) {
            return JsonResult.fail("ids 不能为空！");
        }
        return uploadService.removeByIdsEntity(idsPO.getIds());
    }

    /**
     * 文件上传预加载数据
     * @return
     */
    // @ApiOperation("文件上传预加载数据")
    // @GetMapping("/upload/preparedData")
    // public JsonResult<?> preparedData() {
    //   return uploadService.preparedData();
    // }

}
